package com.loveyukari.service;

import com.loveyukari.dao.IpCoolDao;
import com.loveyukari.model.IpCool;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class IpCoolService {

    private Logger logger = LoggerFactory.getLogger(IpCoolService.class);

    @Autowired
    private IpCoolDao ipCoolDao;
    @Autowired
    private BaiduMapService baiduMapService;

    private String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."+
            "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
            "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
            "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

    public IpCool getIpCool(String ip){
        if (StringUtils.isBlank(ip)){
            return null;
        }
        if (!ip.matches(regex)){
            return null;
        }
        IpCool ipCool = ipCoolDao.select(ip);
        if (ipCool == null){
            ipCool = createIpCool(ip);
            if (ipCool != null){
                ipCoolDao.insert(ipCool);
            }
        } else {
            if (ipCool.getUpdateTime().getTime() < DateUtils.addDays(new Date(),-7).getTime()){
                ipCool = createIpCool(ip);
                if (ipCool != null){
                    ipCoolDao.update(ipCool);
                }
            }
        }
        return ipCool;
    }

    private IpCool createIpCool(String ip){
        JSONObject ipInfo = baiduMapService.getIpInfo(ip);
        if (ipInfo == null || ipInfo.optInt("status") != 0){
            return null;
        }
        IpCool ipCool = null;
        try {
            JSONObject content = ipInfo.optJSONObject("content");
            JSONObject address = content.optJSONObject("address_detail");
            JSONObject point = content.optJSONObject("point");
            ipCool = new IpCool();
            ipCool.setIp(ip);
            ipCool.setCity(address.optString("city"));
            ipCool.setDistrict(address.optString("district"));
            ipCool.setProvince(address.optString("province"));
            ipCool.setPointX(point.optString("x"));
            ipCool.setPointY(point.optString("y"));
            ipCool.setUpdateTime(new Date());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return ipCool;
    }


    public static void main(String[] args) {
        BaiduMapService baiduMapService = new BaiduMapService();
        System.out.println(baiduMapService.getIpInfo("222.67.225.111"));
    }
}
